package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.locals.UserHolder;
import com.leyou.common.utils.JsonUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "cart:add:uid:";

    public void addCart(Cart cart) {
        // 1.获取用户
        UserInfo user = UserHolder.getUser();
        // 2.获取key
        Long userId = user.getId();
        String key = KEY_PREFIX + userId;
        // 3.获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        // 4.获取hashKey，就是商品的id
        String skuId = cart.getSkuId().toString();
        // 5.判断key是否存在
        Boolean isExists = hashOps.hasKey(skuId);
        if (BooleanUtils.isTrue(isExists)) {
            // 需要新增的商品数量
            Integer num = cart.getNum();
            // 存在，取出已经存在的cart
            String json = hashOps.get(skuId);
            cart = JsonUtils.toBean(json, Cart.class);
            // 修改数量
            cart.setNum(cart.getNum() + num);
        }
        // 6.写回redis
        hashOps.put(skuId, JsonUtils.toString(cart));
    }

    public List<Cart> queryCartList() {
        // 1.获取用户
        UserInfo user = UserHolder.getUser();
        // 2.获取key
        Long userId = user.getId();
        String key = KEY_PREFIX + userId;
        // 3.获取hash操作对象
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);

        // 4.获取所有购物车商品
        List<String> values = hashOps.values();
        if (CollectionUtils.isEmpty(values)) {
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        // 5.转换并返回
        return values.stream()
                .map(json -> JsonUtils.toBean(json, Cart.class))
                .collect(Collectors.toList());
    }
}
